package com.kotlin.network.retrofit;

import com.kotlin.network.utils.ToolDateTime;
import com.orhanobut.logger.Logger;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSource;


public class SigningInterceptor implements Interceptor {

	private RetroFactory.ApiType type;

	public SigningInterceptor(RetroFactory.ApiType type) {
		this.type = type;
	}

	@Override
	public Response intercept(Interceptor.Chain chain) throws IOException {

		// 旧的请求
		Request oldRequest = chain.request();
		HttpUrl httpUrl = oldRequest.url();

		//获取请求的参数
		Map<String, Object> paramMap = new HashMap<>();
		for (int i = 0; i < httpUrl.queryParameterNames().size(); i++) {
			paramMap.put(httpUrl.queryParameterName(i), httpUrl.queryParameterValue(i));
		}

		String formatTime = ToolDateTime.formatDateTime(System.currentTimeMillis(), ToolDateTime.DFYYYYMMDDHHMMSS);
		// 添加新的参数
		HttpUrl.Builder authorizedUrlBuilder = httpUrl
				.newBuilder()
				.scheme(oldRequest.url().scheme())
				.host(oldRequest.url().host());


				//.addQueryParameter("random_str", formatTime)
				//.addQueryParameter("sign", StringUtil.createSignCount(formatTime))
				//.addQueryParameter("apptype", NetConstants.apptype)
				//.addQueryParameter("appversion", NetConstants.apiVersion);




		// 新的请求
		Request newRequest = oldRequest.newBuilder()
				.method(oldRequest.method(), oldRequest.body())
				.url(authorizedUrlBuilder.build())
				.build();

		//MyLog.i("RequestUrl",newRequest.url().toString());
		Logger.init("RequestUrl");
		Logger.d(newRequest.url().toString());
		Response response = chain.proceed(newRequest);
		BufferedSource bufferedSource = response.body().source();
		bufferedSource.request(Long.MAX_VALUE);
		Buffer buffer = bufferedSource.buffer();
		//if (BuildConfig.LOG_DEBUG) {
			Logger.init("RequestResponse");
			Logger.d("code = " + response.code() +
					" message = " + response.message() +
					"  url = " + newRequest.url().pathSegments().get(newRequest.url().pathSize() - 1) +
					" body = " + buffer.clone().readString(Charset.forName("UTF-8")));
		//}
		return response;
	}
}